""" user仓储操作 """

from sqlalchemy.orm import Session
from model.user import User
from schema.user import UserCreate
from util import pwd


def get_user(db: Session, user_id: int):
    """ 根据id查询单个用户 """
    return db.query(User).filter(User.id == user_id).first()


def get_user_by_username(db: Session, username: str):
    return db.query(User).filter(User.username == username).first()


def get_users(db: Session):
    """ 获取用户列表 """
    return db.query(User).all()


def create_user(db: Session, user: UserCreate):
    """ 创建用户 """
    # # md5加密
    # encoded_password = hashlib.md5(
    # user.password.encode(encoding='utf-8')).hexdigest()

    encoded_password = pwd.hash_password(user.password)
    new_user = User(username=user.username, password=encoded_password)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user


def delete_user(db: Session, user_id):
    db_user = db.query(User).filter(User.id == user_id).first()
    if db_user:
        db.delete(db_user)
        db.commit()
        db.flush()
        return db_user
